'use client';
import { useEffect, useRef, useState } from 'react';
import './CustomDropdown.scss';

type ThisProps = {
  options: {
    name: string | number;
    value: string | number;
    selected?: boolean;
  }[];
  onSelect: Fn;
};
const CustomDropdown = ({ options, onSelect }: ThisProps) => {
  const [isOpen, setIsOpen] = useState(false);
  const [selected, setSelected] = useState<any>({});
  const [isNearBottom, setIsNearBottom] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const toggleDropdown = () => {
    setIsOpen(prev => !prev);
    if (!isOpen) {
      const isNB =
        window.innerHeight -
          (dropdownRef.current
            ? dropdownRef.current.getBoundingClientRect().bottom
            : 0) <
        150;
      setIsNearBottom(isNB);
    }
  };

  const handleOptionClick = (option: Obj) => {
    setSelected(option);
    setIsOpen(false);
    onSelect && onSelect(option);
  };

  useEffect(() => {
    if (options?.length) {
      const sel = options.find(e => !!e.selected);
      sel ? setSelected(sel) : setSelected(options[0]);
    }
  }, [options]);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return (
    <div className="custom-dropdown" ref={dropdownRef}>
      <div className="dropdown-toggle" onClick={toggleDropdown}>
        <span>{selected?.name}</span>
        <span className="iconfont icon-expand-line"></span>
      </div>
      {isOpen && (
        <ul
          className="dropdown-menu thin-scroll-bar"
          style={{
            top: isNearBottom ? 'auto' : '100%',
            bottom: isNearBottom ? '100%' : 'auto',
          }}
        >
          {options.map((option: Obj, index: number) => (
            <li
              key={index + '_' + option.value}
              className="dropdown-item"
              onClick={() => handleOptionClick(option)}
            >
              {option.name}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default CustomDropdown;
